import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Table, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Tag,
  message,
  Switch,
  Popconfirm,
  Layout ,
  InputNumber,
  Col,
  Row
} from 'antd';
import { 
  PlusOutlined,
  ExclamationCircleOutlined ,
  LogoutOutlined
} from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { 
  createPromotionRule, 
  getPromotionRules,
  togglePromotionRuleStatus
} from '@/store/modules/userStore';

const { Option } = Select;
const { Header } = Layout; // 解构Header组件

const AdminPromotionRules = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [rules, setRules] = useState([]);
  const navigate = useNavigate(); // 获取导航方法
  
  // 获取规则列表
  const fetchRules = async () => {
    setLoading(true);
    try {
      const res = await dispatch(getPromotionRules());

        setRules(res || []);


      
    } catch (error) {
      console.error('获取规则错误:', error);
      message.error('获取规则失败');
    } finally {
      setLoading(false);
    }
  };
  // 登出函数
  const logout = () => {
    // 清除token
    localStorage.removeItem('token');
 
    navigate('/login');
  };

  useEffect(() => {
    fetchRules();
  }, []);

  const conditionTypes = [
    { value: 'time', label: '时间规则' },
    { value: 'seeders', label: '做种人数规则' },
    { value: 'holiday', label: '假期规则' }
  ];

  const actionTypes = [
    { value: 'free_download', label: '免费下载' },
    { value: 'upload_boost', label: '上传加成' },
    { value: 'download_discount', label: '下载折扣' }
  ];

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const params = {
        conditionType: values.conditionType,
        actionType: values.actionType,
        threshold: values.threshold,
        isActive: values.isActive !== false,
        deleteTheSimilar: false,
        ...(values.actionType !== 'free_download' && { 
          value: values.value 
        })
      };

      const res = await dispatch(createPromotionRule(params));

        message.success('规则创建成功');
        fetchRules();
        setIsModalVisible(false);
        form.resetFields();
 
    } catch (error) {
      console.error('提交错误:', error);
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 切换规则状态
  const handleToggleStatus = async (rule) => {
    try {
        console.log(rule)
      setLoading(true);
      const res = await dispatch(togglePromotionRuleStatus({
        id: rule.id,
        isActive: !rule.isActive
      }));
      

        message.success(`规则已${!rule.isActive ? '启用' : '禁用'}`);
        fetchRules(); // 刷新列表
      
    } catch (error) {
      console.error('状态切换错误:', error);
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 辅助函数
  const getRuleTitle = (rule) => {
    const conditionMap = {
      'time': '时间规则',
      'seeders': '做种人数规则',
      'holiday': '假期规则'
    };
    return conditionMap[rule.conditionType] || '促销规则';
  };

  const getRuleDescription = (rule) => {
    if (rule.conditionType === 'time') {
      return `创建${rule.threshold}小时内的种子`;
    } else if (rule.conditionType === 'seeders') {
      return `做种人数少于${rule.threshold}的种子`;
    } else if (rule.conditionType === 'holiday') {
      return '假期期间所有种子';
    }
    return '';
  };

  const getRuleTagColor = (rule) => {
    const actionColors = {
      'free_download': 'green',
      'upload_boost': 'blue',
      'download_discount': 'orange'
    };
    return actionColors[rule.actionType] || 'default';
  };

  const getRuleTagText = (rule) => {
    if (rule.actionType === 'free_download') {
      return '免费下载';
    } else if (rule.actionType === 'upload_boost') {
      return `上传量×${rule.value}`;
    } else if (rule.actionType === 'download_discount') {
      return `下载量${rule.value * 10}折`;
    }
    return '';
  };

  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      render: (_, record) => (
        <div>
          <div>{getRuleTitle(record)}</div>
          <div style={{ fontSize: 12, color: '#999' }}>
            {getRuleDescription(record)}
          </div>
        </div>
      ),
    },
    {
      title: '条件/操作',
      key: 'condition',
      render: (_, record) => (
        <div>
          <div>
            <Tag color="blue">{conditionTypes.find(t => t.value === record.conditionType)?.label}</Tag>
            {record.conditionType !== 'holiday' && (
              <span> {record.threshold}{record.conditionType === 'time' ? '小时' : '人'}</span>
            )}
          </div>
          <div style={{ marginTop: 4 }}>
            <Tag color={getRuleTagColor(record)}>
              {getRuleTagText(record)}
            </Tag>
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive, record) => (
        <Popconfirm
          title={`确定要${isActive ? '禁用' : '启用'}此规则?`}
          onConfirm={() => handleToggleStatus(record)}
          okText="确认"
          cancelText="取消"
          placement="topRight"
        >
          <Switch 
            checked={isActive} 
            checkedChildren="启用" 
            unCheckedChildren="禁用"
          />
        </Popconfirm>
      ),
    }
  ];

  return (
     <Layout>
      {/* 新增固定在顶部的Header */}
      <Header style={{
        position: 'fixed',
        top: 0,
        right: 0,
        left: 0,
        zIndex: 1000,
        display: 'flex',
        justifyContent: 'flex-end',
        alignItems: 'center',
        padding: '0 24px',
        background: '#fff',
        boxShadow: '0 1px 4px rgba(0,21,41,.08)'
      }}>
        <Button 
          danger
          icon={<LogoutOutlined />}
          onClick={() => {
            Modal.confirm({
              title: '确认退出',
              icon: <ExclamationCircleOutlined />,
              content: '确定要退出登录吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: logout
            });
          }}
        >
          退出登录
        </Button>
      </Header>
       <div style={{ paddingTop: '64px', padding: '24px' }}>
    <Card
      title="促销规则管理"
      extra={
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={() => setIsModalVisible(true)}
        >
          添加规则
        </Button>
      }
      loading={loading}
    >
      <Table 
        columns={columns} 
        dataSource={rules} 
        rowKey="id"
        bordered
        pagination={false}
        locale={{
          emptyText: '暂无促销规则'
        }}
      />
      
      {/* 创建规则模态框 */}
      <Modal
        title="创建促销规则"
        visible={isModalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        confirmLoading={loading}
        width={700}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ 
            isActive: true,
            value: 1
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="conditionType"
                label="条件类型"
                rules={[{ required: true, message: '请选择条件类型' }]}
              >
                <Select 
                  placeholder="选择条件类型"
                  onChange={() => form.setFieldsValue({ threshold: undefined })}
                >
                  {conditionTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                noStyle
                shouldUpdate={(prev, current) => prev.conditionType !== current.conditionType}
              >
                {({ getFieldValue }) => (
                  getFieldValue('conditionType') !== 'holiday' && (
                    <Form.Item
                      name="threshold"
                      label="条件阈值"
                      rules={[{ 
                        required: true, 
                        message: '请输入阈值' 
                      }]}
                    >
                      <InputNumber 
                        min={0} 
                        style={{ width: '100%' }}
                        placeholder={
                          getFieldValue('conditionType') === 'time' ? 
                          '小时数' : '做种人数'
                        }
                        precision={1}
                        step={0.1}
                      />
                    </Form.Item>
                  )
                )}
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="actionType"
                label="操作类型"
                rules={[{ required: true, message: '请选择操作类型' }]}
              >
                <Select 
                  placeholder="选择操作类型"
                  onChange={() => form.setFieldsValue({ value: 1 })}
                >
                  {actionTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                noStyle
                shouldUpdate={(prev, current) => prev.actionType !== current.actionType}
              >
                {({ getFieldValue }) => (
                  getFieldValue('actionType') !== 'free_download' && (
                    <Form.Item
                      name="value"
                      label={
                        getFieldValue('actionType') === 'upload_boost' ? 
                        '加成倍数' : '折扣率'
                      }
                      rules={[{ 
                        required: true, 
                        message: '请输入数值',
                        validator: (_, value) => {
                          if (getFieldValue('actionType') === 'upload_boost' && (value < 1 || value > 10)) {
                            return Promise.reject(new Error('请输入1-10之间的数值'));
                          }
                          if (getFieldValue('actionType') === 'download_discount' && (value < 0.1 || value > 0.9)) {
                            return Promise.reject(new Error('请输入0.1-0.9之间的数值'));
                          }
                          return Promise.resolve();
                        }
                      }]}
                    >
                      <InputNumber 
                        min={getFieldValue('actionType') === 'upload_boost' ? 1 : 0.1}
                        max={getFieldValue('actionType') === 'upload_boost' ? 10 : 0.9}
                        step={0.1}
                        style={{ width: '100%' }}
                        precision={1}
                      />
                    </Form.Item>
                  )
                )}
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="isActive"
            label="状态"
            valuePropName="checked"
          >
            <Switch 
              checkedChildren="启用" 
              unCheckedChildren="禁用" 
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
    </div>
      </Layout>
  );
};

export default AdminPromotionRules;